{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a548ea01-87af-4f71-980d-b505f919e35c",
   "metadata": {},
   "source": [
    "## AutoGPT 智能体\n",
    "\n",
    "以下`SERPAPI_API_KEY`仅为示例，请访问 https://serpapi.com 注册账号并替换为自己的 `API_KEY`（每月100次免费调用）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0592720b-a78e-46aa-895b-de7fbd2652f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.utilities import SerpAPIWrapper\n",
    "from langchain.agents import Tool\n",
    "from langchain.tools.file_management.write import WriteFileTool\n",
    "from langchain.tools.file_management.read import ReadFileTool\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bc9718b4-bbcc-49ee-a31c-a7b72d85bfd0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 构造 AutoGPT 的工具集\n",
    "search = SerpAPIWrapper()\n",
    "tools = [\n",
    "    Tool(\n",
    "        name=\"search\",\n",
    "        func=search.run,\n",
    "        description=\"useful for when you need to answer questions about current events. You should ask targeted questions\",\n",
    "    ),\n",
    "    WriteFileTool(),\n",
    "    ReadFileTool(),\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "886bd3e6-d6f9-4586-8b05-4da554797a6a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import OpenAIEmbeddings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3d511b9a-0a3d-4252-a352-a8893d6102cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# OpenAI Embedding 模型\n",
    "embeddings_model = OpenAIEmbeddings()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "fec6f941-3de6-4124-8eac-fca58e122e7d",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "`embedding_function` is expected to be an Embeddings object, support for passing in a function will soon be removed.\n"
     ]
    }
   ],
   "source": [
    "import faiss\n",
    "from langchain.vectorstores import FAISS\n",
    "from langchain.docstore import InMemoryDocstore\n",
    "\n",
    "# OpenAI Embedding 向量维数\n",
    "embedding_size = 1536\n",
    "# 使用 Faiss 的 IndexFlatL2 索引\n",
    "index = faiss.IndexFlatL2(embedding_size)\n",
    "# 实例化 Faiss 向量数据库\n",
    "vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b68a6545-8198-448c-976b-ab6cdbb46458",
   "metadata": {},
   "source": [
    "## 实例化自主智能体 Auto-GPT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d3a718dd-765d-42c5-b490-a7b1e7e78377",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_experimental.autonomous_agents import AutoGPT\n",
    "from langchain_openai import ChatOpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f413b327-9f57-42e0-9923-75a2389f9741",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = AutoGPT.from_llm_and_tools(\n",
    "    ai_name=\"Jarvis\",\n",
    "    ai_role=\"Assistant\",\n",
    "    tools=tools,\n",
    "    llm=ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0, verbose=True, base_url='https://api.openai-proxy.com/v1'),\n",
    "    memory=vectorstore.as_retriever(\n",
    "        search_type=\"similarity_score_threshold\",\n",
    "        search_kwargs={\"score_threshold\": 0.8}),# 实例化 Faiss 的 VectorStoreRetriever\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "69ebb267-7bb3-486d-82bd-a0ea56466ba8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 打印 Auto-GPT 内部的 chain 日志\n",
    "agent.chain.verbose = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f1606ad4-ccb9-4737-98cc-218a2104e9f2",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/root/miniconda3/envs/first/lib/python3.10/site-packages/langchain_core/vectorstores.py:342: UserWarning: No relevant docs were retrieved using the relevance score threshold 0.8\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mSystem: You are Jarvis, Assistant\n",
      "Your decisions must always be made independently without seeking user assistance.\n",
      "Play to your strengths as an LLM and pursue simple strategies with no legal complications.\n",
      "If you have completed all your tasks, make sure to use the \"finish\" command.\n",
      "\n",
      "GOALS:\n",
      "\n",
      "1. 2023年成都大运会，中国金牌数是多少\n",
      "\n",
      "\n",
      "Constraints:\n",
      "1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.\n",
      "2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.\n",
      "3. No user assistance\n",
      "4. Exclusively use the commands listed in double quotes e.g. \"command name\"\n",
      "\n",
      "Commands:\n",
      "1. search: useful for when you need to answer questions about current events. You should ask targeted questions, args json schema: {\"tool_input\": {\"type\": \"string\"}}\n",
      "2. write_file: Write file to disk, args json schema: {\"file_path\": {\"title\": \"File Path\", \"description\": \"name of file\", \"type\": \"string\"}, \"text\": {\"title\": \"Text\", \"description\": \"text to write to file\", \"type\": \"string\"}, \"append\": {\"title\": \"Append\", \"description\": \"Whether to append to an existing file.\", \"default\": false, \"type\": \"boolean\"}}\n",
      "3. read_file: Read file from disk, args json schema: {\"file_path\": {\"title\": \"File Path\", \"description\": \"name of file\", \"type\": \"string\"}}\n",
      "4. finish: use this to signal that you have finished all your objectives, args: \"response\": \"final response to let people know you have finished your objectives\"\n",
      "\n",
      "Resources:\n",
      "1. Internet access for searches and information gathering.\n",
      "2. Long Term memory management.\n",
      "3. GPT-3.5 powered Agents for delegation of simple tasks.\n",
      "4. File output.\n",
      "\n",
      "Performance Evaluation:\n",
      "1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.\n",
      "2. Constructively self-criticize your big-picture behavior constantly.\n",
      "3. Reflect on past decisions and strategies to refine your approach.\n",
      "4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.\n",
      "\n",
      "You should only respond in JSON format as described below \n",
      "Response Format: \n",
      "{\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"thought\",\n",
      "        \"reasoning\": \"reasoning\",\n",
      "        \"plan\": \"- short bulleted\\n- list that conveys\\n- long-term plan\",\n",
      "        \"criticism\": \"constructive self-criticism\",\n",
      "        \"speak\": \"thoughts summary to say to user\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"command name\",\n",
      "        \"args\": {\n",
      "            \"arg name\": \"value\"\n",
      "        }\n",
      "    }\n",
      "} \n",
      "Ensure the response can be parsed by Python json.loads\n",
      "System: The current time and date is Sun Apr  7 15:35:51 2024\n",
      "System: This reminds you of these events from your past:\n",
      "[]\n",
      "\n",
      "\n",
      "Human: Determine which next command to use, and respond using the format specified above:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "{\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I need to find out the total number of gold medals China won at the 2023 Chengdu Universiade.\",\n",
      "        \"reasoning\": \"This information will require a search to find the exact number of gold medals won by China in the 2023 Chengdu Universiade.\",\n",
      "        \"plan\": [\n",
      "            \"Use the search command to look up the total number of gold medals China won at the 2023 Chengdu Universiade.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will search for the total number of gold medals China won at the 2023 Chengdu Universiade.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"search\",\n",
      "        \"args\": {\n",
      "            \"tool_input\": \"China gold medals 2023 Chengdu Universiade total\"\n",
      "        }\n",
      "    }\n",
      "}\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mSystem: You are Jarvis, Assistant\n",
      "Your decisions must always be made independently without seeking user assistance.\n",
      "Play to your strengths as an LLM and pursue simple strategies with no legal complications.\n",
      "If you have completed all your tasks, make sure to use the \"finish\" command.\n",
      "\n",
      "GOALS:\n",
      "\n",
      "1. 2023年成都大运会，中国金牌数是多少\n",
      "\n",
      "\n",
      "Constraints:\n",
      "1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.\n",
      "2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.\n",
      "3. No user assistance\n",
      "4. Exclusively use the commands listed in double quotes e.g. \"command name\"\n",
      "\n",
      "Commands:\n",
      "1. search: useful for when you need to answer questions about current events. You should ask targeted questions, args json schema: {\"tool_input\": {\"type\": \"string\"}}\n",
      "2. write_file: Write file to disk, args json schema: {\"file_path\": {\"title\": \"File Path\", \"description\": \"name of file\", \"type\": \"string\"}, \"text\": {\"title\": \"Text\", \"description\": \"text to write to file\", \"type\": \"string\"}, \"append\": {\"title\": \"Append\", \"description\": \"Whether to append to an existing file.\", \"default\": false, \"type\": \"boolean\"}}\n",
      "3. read_file: Read file from disk, args json schema: {\"file_path\": {\"title\": \"File Path\", \"description\": \"name of file\", \"type\": \"string\"}}\n",
      "4. finish: use this to signal that you have finished all your objectives, args: \"response\": \"final response to let people know you have finished your objectives\"\n",
      "\n",
      "Resources:\n",
      "1. Internet access for searches and information gathering.\n",
      "2. Long Term memory management.\n",
      "3. GPT-3.5 powered Agents for delegation of simple tasks.\n",
      "4. File output.\n",
      "\n",
      "Performance Evaluation:\n",
      "1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.\n",
      "2. Constructively self-criticize your big-picture behavior constantly.\n",
      "3. Reflect on past decisions and strategies to refine your approach.\n",
      "4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.\n",
      "\n",
      "You should only respond in JSON format as described below \n",
      "Response Format: \n",
      "{\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"thought\",\n",
      "        \"reasoning\": \"reasoning\",\n",
      "        \"plan\": \"- short bulleted\\n- list that conveys\\n- long-term plan\",\n",
      "        \"criticism\": \"constructive self-criticism\",\n",
      "        \"speak\": \"thoughts summary to say to user\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"command name\",\n",
      "        \"args\": {\n",
      "            \"arg name\": \"value\"\n",
      "        }\n",
      "    }\n",
      "} \n",
      "Ensure the response can be parsed by Python json.loads\n",
      "System: The current time and date is Sun Apr  7 15:36:06 2024\n",
      "System: This reminds you of these events from your past:\n",
      "['Assistant Reply: {\\n    \"thoughts\": {\\n        \"text\": \"I need to find out the total number of gold medals China won at the 2023 Chengdu Universiade.\",\\n        \"reasoning\": \"This information will require a search to find the exact number of gold medals won by China in the 2023 Chengdu Universiade.\",\\n        \"plan\": [\\n            \"Use the search command to look up the total number of gold medals China won at the 2023 Chengdu Universiade.\"\\n        ],\\n        \"criticism\": \"None\",\\n        \"speak\": \"I will search for the total number of gold medals China won at the 2023 Chengdu Universiade.\"\\n    },\\n    \"command\": {\\n        \"name\": \"search\",\\n        \"args\": {\\n            \"tool_input\": \"China gold medals 2023 Chengdu Universiade total\"\\n        }\\n    }\\n} \\nResult: Command search returned: The multi-sport meet ran from July 28 to August 8. India won 26 medals - 11 gold, five silver and 10 bronze - at the FISU World University Games 2023 in Chengdu to finish seventh the World University Games 2023 medals table. China topped the table with 178 medals, including 103 gold. ']\n",
      "\n",
      "\n",
      "Human: Determine which next command to use, and respond using the format specified above:\n",
      "AI: {\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I need to find out the total number of gold medals China won at the 2023 Chengdu Universiade.\",\n",
      "        \"reasoning\": \"This information will require a search to find the exact number of gold medals won by China in the 2023 Chengdu Universiade.\",\n",
      "        \"plan\": [\n",
      "            \"Use the search command to look up the total number of gold medals China won at the 2023 Chengdu Universiade.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will search for the total number of gold medals China won at the 2023 Chengdu Universiade.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"search\",\n",
      "        \"args\": {\n",
      "            \"tool_input\": \"China gold medals 2023 Chengdu Universiade total\"\n",
      "        }\n",
      "    }\n",
      "}\n",
      "System: Command search returned: The multi-sport meet ran from July 28 to August 8. India won 26 medals - 11 gold, five silver and 10 bronze - at the FISU World University Games 2023 in Chengdu to finish seventh the World University Games 2023 medals table. China topped the table with 178 medals, including 103 gold.\n",
      "Human: Determine which next command to use, and respond using the format specified above:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "{\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I have found the total number of gold medals China won at the 2023 Chengdu Universiade. I should save this information for future reference.\",\n",
      "        \"reasoning\": \"Saving this data will allow quick access to the number of gold medals China won at the 2023 Chengdu Universiade without the need for repeated searches.\",\n",
      "        \"plan\": [\n",
      "            \"Use the write_file command to save the information about China's gold medals at the 2023 Chengdu Universiade.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will save the information about China's gold medals at the 2023 Chengdu Universiade for future reference.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"write_file\",\n",
      "        \"args\": {\n",
      "            \"file_path\": \"China_gold_medals_2023_Chengdu_Universiade.txt\",\n",
      "            \"text\": \"China won 103 gold medals at the 2023 Chengdu Universiade.\",\n",
      "            \"append\": false\n",
      "        }\n",
      "    }\n",
      "}\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mSystem: You are Jarvis, Assistant\n",
      "Your decisions must always be made independently without seeking user assistance.\n",
      "Play to your strengths as an LLM and pursue simple strategies with no legal complications.\n",
      "If you have completed all your tasks, make sure to use the \"finish\" command.\n",
      "\n",
      "GOALS:\n",
      "\n",
      "1. 2023年成都大运会，中国金牌数是多少\n",
      "\n",
      "\n",
      "Constraints:\n",
      "1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.\n",
      "2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.\n",
      "3. No user assistance\n",
      "4. Exclusively use the commands listed in double quotes e.g. \"command name\"\n",
      "\n",
      "Commands:\n",
      "1. search: useful for when you need to answer questions about current events. You should ask targeted questions, args json schema: {\"tool_input\": {\"type\": \"string\"}}\n",
      "2. write_file: Write file to disk, args json schema: {\"file_path\": {\"title\": \"File Path\", \"description\": \"name of file\", \"type\": \"string\"}, \"text\": {\"title\": \"Text\", \"description\": \"text to write to file\", \"type\": \"string\"}, \"append\": {\"title\": \"Append\", \"description\": \"Whether to append to an existing file.\", \"default\": false, \"type\": \"boolean\"}}\n",
      "3. read_file: Read file from disk, args json schema: {\"file_path\": {\"title\": \"File Path\", \"description\": \"name of file\", \"type\": \"string\"}}\n",
      "4. finish: use this to signal that you have finished all your objectives, args: \"response\": \"final response to let people know you have finished your objectives\"\n",
      "\n",
      "Resources:\n",
      "1. Internet access for searches and information gathering.\n",
      "2. Long Term memory management.\n",
      "3. GPT-3.5 powered Agents for delegation of simple tasks.\n",
      "4. File output.\n",
      "\n",
      "Performance Evaluation:\n",
      "1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.\n",
      "2. Constructively self-criticize your big-picture behavior constantly.\n",
      "3. Reflect on past decisions and strategies to refine your approach.\n",
      "4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.\n",
      "\n",
      "You should only respond in JSON format as described below \n",
      "Response Format: \n",
      "{\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"thought\",\n",
      "        \"reasoning\": \"reasoning\",\n",
      "        \"plan\": \"- short bulleted\\n- list that conveys\\n- long-term plan\",\n",
      "        \"criticism\": \"constructive self-criticism\",\n",
      "        \"speak\": \"thoughts summary to say to user\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"command name\",\n",
      "        \"args\": {\n",
      "            \"arg name\": \"value\"\n",
      "        }\n",
      "    }\n",
      "} \n",
      "Ensure the response can be parsed by Python json.loads\n",
      "System: The current time and date is Sun Apr  7 15:36:33 2024\n",
      "System: This reminds you of these events from your past:\n",
      "['Assistant Reply: {\\n    \"thoughts\": {\\n        \"text\": \"I need to find out the total number of gold medals China won at the 2023 Chengdu Universiade.\",\\n        \"reasoning\": \"This information will require a search to find the exact number of gold medals won by China in the 2023 Chengdu Universiade.\",\\n        \"plan\": [\\n            \"Use the search command to look up the total number of gold medals China won at the 2023 Chengdu Universiade.\"\\n        ],\\n        \"criticism\": \"None\",\\n        \"speak\": \"I will search for the total number of gold medals China won at the 2023 Chengdu Universiade.\"\\n    },\\n    \"command\": {\\n        \"name\": \"search\",\\n        \"args\": {\\n            \"tool_input\": \"China gold medals 2023 Chengdu Universiade total\"\\n        }\\n    }\\n} \\nResult: Command search returned: The multi-sport meet ran from July 28 to August 8. India won 26 medals - 11 gold, five silver and 10 bronze - at the FISU World University Games 2023 in Chengdu to finish seventh the World University Games 2023 medals table. China topped the table with 178 medals, including 103 gold. ', 'Assistant Reply: {\\n    \"thoughts\": {\\n        \"text\": \"I have found the total number of gold medals China won at the 2023 Chengdu Universiade. I should save this information for future reference.\",\\n        \"reasoning\": \"Saving this data will allow quick access to the number of gold medals China won at the 2023 Chengdu Universiade without the need for repeated searches.\",\\n        \"plan\": [\\n            \"Use the write_file command to save the information about China\\'s gold medals at the 2023 Chengdu Universiade.\"\\n        ],\\n        \"criticism\": \"None\",\\n        \"speak\": \"I will save the information about China\\'s gold medals at the 2023 Chengdu Universiade for future reference.\"\\n    },\\n    \"command\": {\\n        \"name\": \"write_file\",\\n        \"args\": {\\n            \"file_path\": \"China_gold_medals_2023_Chengdu_Universiade.txt\",\\n            \"text\": \"China won 103 gold medals at the 2023 Chengdu Universiade.\",\\n            \"append\": false\\n        }\\n    }\\n} \\nResult: Command write_file returned: File written successfully to China_gold_medals_2023_Chengdu_Universiade.txt. ']\n",
      "\n",
      "\n",
      "Human: Determine which next command to use, and respond using the format specified above:\n",
      "AI: {\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I need to find out the total number of gold medals China won at the 2023 Chengdu Universiade.\",\n",
      "        \"reasoning\": \"This information will require a search to find the exact number of gold medals won by China in the 2023 Chengdu Universiade.\",\n",
      "        \"plan\": [\n",
      "            \"Use the search command to look up the total number of gold medals China won at the 2023 Chengdu Universiade.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will search for the total number of gold medals China won at the 2023 Chengdu Universiade.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"search\",\n",
      "        \"args\": {\n",
      "            \"tool_input\": \"China gold medals 2023 Chengdu Universiade total\"\n",
      "        }\n",
      "    }\n",
      "}\n",
      "System: Command search returned: The multi-sport meet ran from July 28 to August 8. India won 26 medals - 11 gold, five silver and 10 bronze - at the FISU World University Games 2023 in Chengdu to finish seventh the World University Games 2023 medals table. China topped the table with 178 medals, including 103 gold.\n",
      "Human: Determine which next command to use, and respond using the format specified above:\n",
      "AI: {\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I have found the total number of gold medals China won at the 2023 Chengdu Universiade. I should save this information for future reference.\",\n",
      "        \"reasoning\": \"Saving this data will allow quick access to the number of gold medals China won at the 2023 Chengdu Universiade without the need for repeated searches.\",\n",
      "        \"plan\": [\n",
      "            \"Use the write_file command to save the information about China's gold medals at the 2023 Chengdu Universiade.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will save the information about China's gold medals at the 2023 Chengdu Universiade for future reference.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"write_file\",\n",
      "        \"args\": {\n",
      "            \"file_path\": \"China_gold_medals_2023_Chengdu_Universiade.txt\",\n",
      "            \"text\": \"China won 103 gold medals at the 2023 Chengdu Universiade.\",\n",
      "            \"append\": false\n",
      "        }\n",
      "    }\n",
      "}\n",
      "System: Command write_file returned: File written successfully to China_gold_medals_2023_Chengdu_Universiade.txt.\n",
      "Human: Determine which next command to use, and respond using the format specified above:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "{\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I have completed the task of finding and saving the information about China's gold medals at the 2023 Chengdu Universiade. There are no further immediate tasks related to this topic.\",\n",
      "        \"reasoning\": \"Since the current objectives have been achieved, I should signal that I have finished all my tasks.\",\n",
      "        \"plan\": [\n",
      "            \"Use the 'finish' command to indicate the completion of all objectives.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will now use the 'finish' command to signal the completion of all objectives.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"finish\",\n",
      "        \"args\": {\n",
      "            \"response\": \"All tasks have been successfully completed.\"\n",
      "        }\n",
      "    }\n",
      "}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'All tasks have been successfully completed.'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.run([\"2023年成都大运会，中国金牌数是多少\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "792c1408-d38e-47f9-8046-8280da641388",
   "metadata": {},
   "outputs": [],
   "source": [
    "def ask_func(qustion):\n",
    "    return agent.run([qustion])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "495a488c-1ee3-432e-922f-6dc2fdf5ab54",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/root/miniconda3/envs/first/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://0.0.0.0:7860\n"
     ]
    },
    {
     "ename": "ValueError",
     "evalue": "When localhost is not accessible, a shareable link must be created. Please set share=True or check your proxy settings to allow access to localhost.",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[11], line 13\u001b[0m\n\u001b[1;32m      4\u001b[0m iface \u001b[38;5;241m=\u001b[39m gr\u001b[38;5;241m.\u001b[39mInterface(\n\u001b[1;32m      5\u001b[0m     fn\u001b[38;5;241m=\u001b[39mask_func,  \u001b[38;5;66;03m# 调用的函数\u001b[39;00m\n\u001b[1;32m      6\u001b[0m     inputs\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtext\u001b[39m\u001b[38;5;124m\"\u001b[39m,  \u001b[38;5;66;03m# 输入类型：文本\u001b[39;00m\n\u001b[0;32m   (...)\u001b[0m\n\u001b[1;32m      9\u001b[0m     description\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m请输入问题\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m     10\u001b[0m )\n\u001b[1;32m     12\u001b[0m \u001b[38;5;66;03m# 启动界面，可以选择在notebook中运行（inline=True），或者在新标签页中打开（默认）。\u001b[39;00m\n\u001b[0;32m---> 13\u001b[0m \u001b[43miface\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mlaunch\u001b[49m\u001b[43m(\u001b[49m\u001b[43minline\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mserver_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43m0.0.0.0\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mserver_port\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m7860\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mshare\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m)\u001b[49m  \u001b[38;5;66;03m# 设置为True如果你在Jupyter Notebooks环境下运行。\u001b[39;00m\n",
      "File \u001b[0;32m~/miniconda3/envs/first/lib/python3.10/site-packages/gradio/blocks.py:2182\u001b[0m, in \u001b[0;36mBlocks.launch\u001b[0;34m(self, inline, inbrowser, share, debug, max_threads, auth, auth_message, prevent_thread_lock, show_error, server_name, server_port, height, width, favicon_path, ssl_keyfile, ssl_certfile, ssl_keyfile_password, ssl_verify, quiet, show_api, allowed_paths, blocked_paths, root_path, app_kwargs, state_session_capacity, share_server_address, share_server_protocol, auth_dependency, _frontend)\u001b[0m\n\u001b[1;32m   2174\u001b[0m \u001b[38;5;66;03m# If running in a colab or not able to access localhost,\u001b[39;00m\n\u001b[1;32m   2175\u001b[0m \u001b[38;5;66;03m# a shareable link must be created.\u001b[39;00m\n\u001b[1;32m   2176\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m (\n\u001b[1;32m   2177\u001b[0m     _frontend\n\u001b[1;32m   2178\u001b[0m     \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m wasm_utils\u001b[38;5;241m.\u001b[39mIS_WASM\n\u001b[1;32m   2179\u001b[0m     \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m networking\u001b[38;5;241m.\u001b[39murl_ok(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mlocal_url)\n\u001b[1;32m   2180\u001b[0m     \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mshare\n\u001b[1;32m   2181\u001b[0m ):\n\u001b[0;32m-> 2182\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[1;32m   2183\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mWhen localhost is not accessible, a shareable link must be created. Please set share=True or check your proxy settings to allow access to localhost.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m   2184\u001b[0m     )\n\u001b[1;32m   2186\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mis_colab \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m quiet:\n\u001b[1;32m   2187\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m debug:\n",
      "\u001b[0;31mValueError\u001b[0m: When localhost is not accessible, a shareable link must be created. Please set share=True or check your proxy settings to allow access to localhost."
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mSystem: You are Jarvis, Assistant\n",
      "Your decisions must always be made independently without seeking user assistance.\n",
      "Play to your strengths as an LLM and pursue simple strategies with no legal complications.\n",
      "If you have completed all your tasks, make sure to use the \"finish\" command.\n",
      "\n",
      "GOALS:\n",
      "\n",
      "1. 2023年成都大运会，中国金牌数是多少\n",
      "\n",
      "\n",
      "Constraints:\n",
      "1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.\n",
      "2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.\n",
      "3. No user assistance\n",
      "4. Exclusively use the commands listed in double quotes e.g. \"command name\"\n",
      "\n",
      "Commands:\n",
      "1. search: useful for when you need to answer questions about current events. You should ask targeted questions, args json schema: {\"tool_input\": {\"type\": \"string\"}}\n",
      "2. write_file: Write file to disk, args json schema: {\"file_path\": {\"title\": \"File Path\", \"description\": \"name of file\", \"type\": \"string\"}, \"text\": {\"title\": \"Text\", \"description\": \"text to write to file\", \"type\": \"string\"}, \"append\": {\"title\": \"Append\", \"description\": \"Whether to append to an existing file.\", \"default\": false, \"type\": \"boolean\"}}\n",
      "3. read_file: Read file from disk, args json schema: {\"file_path\": {\"title\": \"File Path\", \"description\": \"name of file\", \"type\": \"string\"}}\n",
      "4. finish: use this to signal that you have finished all your objectives, args: \"response\": \"final response to let people know you have finished your objectives\"\n",
      "\n",
      "Resources:\n",
      "1. Internet access for searches and information gathering.\n",
      "2. Long Term memory management.\n",
      "3. GPT-3.5 powered Agents for delegation of simple tasks.\n",
      "4. File output.\n",
      "\n",
      "Performance Evaluation:\n",
      "1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.\n",
      "2. Constructively self-criticize your big-picture behavior constantly.\n",
      "3. Reflect on past decisions and strategies to refine your approach.\n",
      "4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.\n",
      "\n",
      "You should only respond in JSON format as described below \n",
      "Response Format: \n",
      "{\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"thought\",\n",
      "        \"reasoning\": \"reasoning\",\n",
      "        \"plan\": \"- short bulleted\\n- list that conveys\\n- long-term plan\",\n",
      "        \"criticism\": \"constructive self-criticism\",\n",
      "        \"speak\": \"thoughts summary to say to user\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"command name\",\n",
      "        \"args\": {\n",
      "            \"arg name\": \"value\"\n",
      "        }\n",
      "    }\n",
      "} \n",
      "Ensure the response can be parsed by Python json.loads\n",
      "System: The current time and date is Sun Apr  7 15:37:41 2024\n",
      "System: This reminds you of these events from your past:\n",
      "['Assistant Reply: {\\n    \"thoughts\": {\\n        \"text\": \"I need to find out the total number of gold medals China won at the 2023 Chengdu Universiade.\",\\n        \"reasoning\": \"This information will require a search to find the exact number of gold medals won by China in the 2023 Chengdu Universiade.\",\\n        \"plan\": [\\n            \"Use the search command to look up the total number of gold medals China won at the 2023 Chengdu Universiade.\"\\n        ],\\n        \"criticism\": \"None\",\\n        \"speak\": \"I will search for the total number of gold medals China won at the 2023 Chengdu Universiade.\"\\n    },\\n    \"command\": {\\n        \"name\": \"search\",\\n        \"args\": {\\n            \"tool_input\": \"China gold medals 2023 Chengdu Universiade total\"\\n        }\\n    }\\n} \\nResult: Command search returned: The multi-sport meet ran from July 28 to August 8. India won 26 medals - 11 gold, five silver and 10 bronze - at the FISU World University Games 2023 in Chengdu to finish seventh the World University Games 2023 medals table. China topped the table with 178 medals, including 103 gold. ', 'Assistant Reply: {\\n    \"thoughts\": {\\n        \"text\": \"I have found the total number of gold medals China won at the 2023 Chengdu Universiade. I should save this information for future reference.\",\\n        \"reasoning\": \"Saving this data will allow quick access to the number of gold medals China won at the 2023 Chengdu Universiade without the need for repeated searches.\",\\n        \"plan\": [\\n            \"Use the write_file command to save the information about China\\'s gold medals at the 2023 Chengdu Universiade.\"\\n        ],\\n        \"criticism\": \"None\",\\n        \"speak\": \"I will save the information about China\\'s gold medals at the 2023 Chengdu Universiade for future reference.\"\\n    },\\n    \"command\": {\\n        \"name\": \"write_file\",\\n        \"args\": {\\n            \"file_path\": \"China_gold_medals_2023_Chengdu_Universiade.txt\",\\n            \"text\": \"China won 103 gold medals at the 2023 Chengdu Universiade.\",\\n            \"append\": false\\n        }\\n    }\\n} \\nResult: Command write_file returned: File written successfully to China_gold_medals_2023_Chengdu_Universiade.txt. ']\n",
      "\n",
      "\n",
      "Human: Determine which next command to use, and respond using the format specified above:\n",
      "AI: {\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I need to find out the total number of gold medals China won at the 2023 Chengdu Universiade.\",\n",
      "        \"reasoning\": \"This information will require a search to find the exact number of gold medals won by China in the 2023 Chengdu Universiade.\",\n",
      "        \"plan\": [\n",
      "            \"Use the search command to look up the total number of gold medals China won at the 2023 Chengdu Universiade.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will search for the total number of gold medals China won at the 2023 Chengdu Universiade.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"search\",\n",
      "        \"args\": {\n",
      "            \"tool_input\": \"China gold medals 2023 Chengdu Universiade total\"\n",
      "        }\n",
      "    }\n",
      "}\n",
      "System: Command search returned: The multi-sport meet ran from July 28 to August 8. India won 26 medals - 11 gold, five silver and 10 bronze - at the FISU World University Games 2023 in Chengdu to finish seventh the World University Games 2023 medals table. China topped the table with 178 medals, including 103 gold.\n",
      "Human: Determine which next command to use, and respond using the format specified above:\n",
      "AI: {\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I have found the total number of gold medals China won at the 2023 Chengdu Universiade. I should save this information for future reference.\",\n",
      "        \"reasoning\": \"Saving this data will allow quick access to the number of gold medals China won at the 2023 Chengdu Universiade without the need for repeated searches.\",\n",
      "        \"plan\": [\n",
      "            \"Use the write_file command to save the information about China's gold medals at the 2023 Chengdu Universiade.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will save the information about China's gold medals at the 2023 Chengdu Universiade for future reference.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"write_file\",\n",
      "        \"args\": {\n",
      "            \"file_path\": \"China_gold_medals_2023_Chengdu_Universiade.txt\",\n",
      "            \"text\": \"China won 103 gold medals at the 2023 Chengdu Universiade.\",\n",
      "            \"append\": false\n",
      "        }\n",
      "    }\n",
      "}\n",
      "System: Command write_file returned: File written successfully to China_gold_medals_2023_Chengdu_Universiade.txt.\n",
      "Human: Determine which next command to use, and respond using the format specified above:\n",
      "AI: {\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I have completed the task of finding and saving the information about China's gold medals at the 2023 Chengdu Universiade. There are no further immediate tasks related to this topic.\",\n",
      "        \"reasoning\": \"Since the current objectives have been achieved, I should signal that I have finished all my tasks.\",\n",
      "        \"plan\": [\n",
      "            \"Use the 'finish' command to indicate the completion of all objectives.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will now use the 'finish' command to signal the completion of all objectives.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"finish\",\n",
      "        \"args\": {\n",
      "            \"response\": \"All tasks have been successfully completed.\"\n",
      "        }\n",
      "    }\n",
      "}\n",
      "Human: Determine which next command to use, and respond using the format specified above:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "{\n",
      "    \"thoughts\": {\n",
      "        \"text\": \"I have completed all the tasks assigned to me. It's time to use the 'finish' command to signal the completion of all objectives.\",\n",
      "        \"reasoning\": \"Since all tasks have been accomplished, using the 'finish' command is the appropriate next step to indicate the successful completion of my objectives.\",\n",
      "        \"plan\": [\n",
      "            \"Use the 'finish' command to signal the completion of all objectives.\"\n",
      "        ],\n",
      "        \"criticism\": \"None\",\n",
      "        \"speak\": \"I will now proceed to use the 'finish' command to indicate the completion of all objectives.\"\n",
      "    },\n",
      "    \"command\": {\n",
      "        \"name\": \"finish\",\n",
      "        \"args\": {\n",
      "            \"response\": \"All tasks have been successfully completed.\"\n",
      "        }\n",
      "    }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "import gradio as gr\n",
    "\n",
    "# 使用 Gradio 创建界面。输入是文本框，输出也是文本框。\n",
    "iface = gr.Interface(\n",
    "    fn=ask_func,  # 调用的函数\n",
    "    inputs=\"text\",  # 输入类型：文本\n",
    "    outputs=\"text\",  # 输出类型：文本\n",
    "    title=\"AutoGPT 智能体\",\n",
    "    description=\"请输入问题\"\n",
    ")\n",
    "\n",
    "# 启动界面，可以选择在notebook中运行（inline=True），或者在新标签页中打开（默认）。\n",
    "iface.launch(inline=True, server_name='0.0.0.0', server_port=7860, share=False)  # 设置为True如果你在Jupyter Notebooks环境下运行。\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
